package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.emq.MqttService;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {


    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private UserService userService;

    @Autowired
    private MqttProducer mqttProducer;


    /**
     * 获取同一天内分配的工单最少的人
     *
     * @param regionId
     * @param isRepair 是否是运维工单
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        String roleCode = "1002";
        if (isRepair) {  //如果是运维工单
            roleCode = "1003";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF + "." + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + regionId + "." + roleCode;
        Set<Object> set = redisTemplate.opsForZSet().range(key, 0, 1);
        if (key == null || key.isBlank()) {
            throw new LogicException("该区域没有相关人员");
        }
        return (Integer) set.stream().collect(Collectors.toList()).get(0);

    }

    /**
     * 完成工单
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean complete(Long taskId) {
        TaskEntity task = getById(taskId);
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH && task.getTaskStatus() == VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("工单已结束");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        this.updateById(task);
        //如果是投放工单 和 撤机工单  向售货机发送消息
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_DEPLOY || task.getProductTypeId() == VMSystem.TASK_TYPE_REVOKE) {
            noticeVMServiceStatus(task);
        }
        //如果是补货工单  向售货机发送消息
        if (task.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            //根据工单id查询工单明细表
            Supply(task);
        }
        return true;
    }


    /**
     * 捕获工单封装与 下发
     *
     * @param task
     */
    private void Supply(TaskEntity task) {
        LambdaQueryWrapper<TaskDetailsEntity> eq = Wrappers.<TaskDetailsEntity>lambdaQuery().eq(TaskDetailsEntity::getTaskId, task.getTaskId());
        List<TaskDetailsEntity> list = taskDetailsService.list(eq);

        SupplyContract contract = new SupplyContract();
        //售货机编号
        contract.setInnerCode(task.getInnerCode());
        //补货货道数据
        ArrayList<SupplyChannel> supplyChannels = Lists.newArrayList();
        list.forEach(d -> {
            SupplyChannel channel = new SupplyChannel();
            //货道编号
            channel.setChannelId(d.getChannelCode());
            //补货数量
            channel.setCapacity(d.getExpectCapacity());
            supplyChannels.add(channel);
        });
        contract.setSupplyData(supplyChannels);
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, contract);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 运维工单封装与下发
     *
     * @param
     */
    private void noticeVMServiceStatus(TaskEntity task) {
        TaskCompleteContract contract = new TaskCompleteContract();
        contract.setInnerCode(task.getInnerCode());
        contract.setTaskType(task.getProductTypeId());
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, contract);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消工单
     *
     * @param taskId
     * @param cancelTaskViewModel
     * @return
     */
    @Override
    public boolean cancel(Long taskId, CancelTaskViewModel cancelTaskViewModel) {
        TaskEntity task = getById(taskId);
        if (task.getTaskStatus() == VMSystem.TASK_STATUS_FINISH && task.getTaskStatus() == VMSystem.TASK_STATUS_CANCEL) {
            throw new LogicException("工单已结束");
        }
        task.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        task.setDesc(cancelTaskViewModel.getDesc());
        updateById(task);
        //更新工单量列表
        updateTaskZSet(task, -1);
        return true;
    }

    /**
     * 接受工单
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean accept(Long taskId) {
        TaskEntity task = getById(taskId);
        if (task.getTaskStatus() != VMSystem.TASK_STATUS_CREATE) {
            throw new LogicException("当前工单不是待处理");
        }
        //设置当前工单为进行时
        task.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        //更新工单量列表
        updateById(task);
        return true;
    }

    /**
     * 创建工单
     *
     * @param taskViewModel
     * @return
     */
    @Override
    @Transactional
    public boolean create(TaskViewModel taskViewModel) {
        //验证售货机
        checkCreateTask(taskViewModel.getInnerCode(), taskViewModel.getProductType());
        if (hasTask(taskViewModel.getInnerCode(), taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }
        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        BeanUtils.copyProperties(taskViewModel, taskEntity);
        //自定义设备编号
        taskEntity.setTaskCode(generateTaskCode());
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        UserVO user = userService.getUser(taskViewModel.getUserId());
        taskEntity.setUserName(user.getUserName());
        //获取售货机信息
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        taskEntity.setAddr(vmInfo.getNodeAddr());
        taskEntity.setRegionId(vmInfo.getRegionId());
        save(taskEntity);

        //如果是补货工单,插入记录
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            taskViewModel.getDetails().forEach(details -> {
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(details, detailsEntity);
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }

        //更新工单量列表
        updateTaskZSet(taskEntity, 1);

        return true;
    }

    /**
     * 更新工单量列表
     *
     * @param task
     * @param score
     */
    private void updateTaskZSet(TaskEntity task, int score) {
        String roleCode = "1003"; //运维员
        //如果是补货工单
        if (task.getProductTypeId().intValue() == 2) {
            roleCode = "1002";//运营员
        }
        String key = VMSystem.REGION_TASK_KEY_PREF + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + task.getRegionId() + "." + roleCode;
        redisTemplate.opsForZSet().incrementScore(key, task.getUserId(), score);
    }

    /**
     * 自定义 设备编号  redis 单线程 保证线程安全
     *
     * @return
     */
    private String generateTaskCode() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "lkd.task.code" + date;
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().setIfAbsent(key, 0l, Duration.ofDays(1));
        }
        return date + String.format("%04d", redisTemplate.opsForValue().increment(key, 1));
    }


    /**
     * 创建工单校验
     *
     * @param innerCode   设备编号
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(String innerCode, int productType) throws LogicException {
        VmVO vmInfo = vmService.getVMInfo(innerCode);//根据设备编号查询设备
        if (vmInfo == null) throw new LogicException("设备校验失败");
        //如果是投放工单，状态为运营
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }

        //如果是补货工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
    }

    /**
     * 同一台设备下是否存在未完成的工单
     *
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode, int productionType) {
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productionType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }

}
